package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysWechatBind;
import com.ruoyi.system.service.ISysWechatBindService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 用户微信绑定Controller
 * 
 * @author ruoyi
 * @date 2025-06-10
 */
@RestController
@RequestMapping("/system/bind")
public class SysWechatBindController extends BaseController
{
    @Autowired
    private ISysWechatBindService sysWechatBindService;

    /**
     * 查询用户微信绑定列表
     */
    @PreAuthorize("@ss.hasPermi('system:bind:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysWechatBind sysWechatBind)
    {
        startPage();
        List<SysWechatBind> list = sysWechatBindService.selectSysWechatBindList(sysWechatBind);
        return getDataTable(list);
    }

    /**
     * 导出用户微信绑定列表
     */
    @PreAuthorize("@ss.hasPermi('system:bind:export')")
    @Log(title = "用户微信绑定", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysWechatBind sysWechatBind)
    {
        List<SysWechatBind> list = sysWechatBindService.selectSysWechatBindList(sysWechatBind);
        ExcelUtil<SysWechatBind> util = new ExcelUtil<SysWechatBind>(SysWechatBind.class);
        util.exportExcel(response, list, "用户微信绑定数据");
    }

    /**
     * 获取用户微信绑定详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:bind:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysWechatBindService.selectSysWechatBindById(id));
    }

    /**
     * 新增用户微信绑定
     */
    @Log(title = "用户微信绑定", businessType = BusinessType.INSERT)
    @PostMapping

    public AjaxResult add(@RequestBody SysWechatBind sysWechatBind)
    {
        return toAjax(sysWechatBindService.insertSysWechatBind(sysWechatBind));
    }

    /**
     * 扫码授权绑定接口
     * 检查用户是否已绑定，如果未绑定则创建绑定记录
     */
    @Anonymous
    @Log(title = "扫码授权绑定", businessType = BusinessType.INSERT)
    @PostMapping("/qr-auth")
    public AjaxResult qrAuthBind(@RequestBody SysWechatBind sysWechatBind)
    {
        try {
            // 参数验证
            if (sysWechatBind.getUserId() == null) {
                return error("用户ID不能为空");
            }
            if (sysWechatBind.getOpenId() == null || sysWechatBind.getOpenId().trim().isEmpty()) {
                return error("OpenID不能为空");
            }

            // 检查是否已经绑定（通过userId和unionId）
            SysWechatBind queryBind = new SysWechatBind();
            queryBind.setUserId(sysWechatBind.getUserId());
            if (sysWechatBind.getUnionId() != null && !sysWechatBind.getUnionId().trim().isEmpty()) {
                queryBind.setUnionId(sysWechatBind.getUnionId());
            }
            
            List<SysWechatBind> existingBinds = sysWechatBindService.selectSysWechatBindList(queryBind);
            
            // 如果已经存在绑定记录
            if (!existingBinds.isEmpty()) {
                SysWechatBind existingBind = existingBinds.get(0);
                
                // 检查绑定状态
                if (existingBind.getBindStatus() != null && existingBind.getBindStatus() == 1) {
                    return error("该用户已经绑定微信，无需重复授权");
                } else {
                    // 如果是解绑状态，重新激活绑定
                    existingBind.setBindStatus(1);
                    existingBind.setLastLoginTime(new Date());
                    existingBind.setNickname(sysWechatBind.getNickname());
                    existingBind.setAvatarUrl(sysWechatBind.getAvatarUrl());
                    existingBind.setPhone(sysWechatBind.getPhone());
                    
                    int result = sysWechatBindService.updateSysWechatBind(existingBind);
                    if (result > 0) {
                        return success("重新绑定成功");
                    } else {
                        return error("重新绑定失败");
                    }
                }
            }
            
            // 创建新的绑定记录
            sysWechatBind.setBindStatus(1); // 设置为已绑定状态
            sysWechatBind.setLastLoginTime(new Date());
            
            int result = sysWechatBindService.insertSysWechatBind(sysWechatBind);
            if (result > 0) {
                return success("授权绑定成功");
            } else {
                return error("授权绑定失败");
            }
            
        } catch (Exception e) {
            logger.error("扫码授权绑定异常", e);
            return error("授权绑定异常：" + e.getMessage());
        }
    }

    /**
     * 修改用户微信绑定
     */
//    @PreAuthorize("@ss.hasPermi('system:bind:edit')")
    @Log(title = "用户微信绑定", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysWechatBind sysWechatBind)
    {
        return toAjax(sysWechatBindService.updateSysWechatBind(sysWechatBind));
    }

    /**
     * 删除用户微信绑定
     */
    @PreAuthorize("@ss.hasPermi('system:bind:remove')")
    @Log(title = "用户微信绑定", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysWechatBindService.deleteSysWechatBindByIds(ids));
    }
}
